package com.dankegongyu.lib.common.widget;

import android.app.Activity;

import com.dankegongyu.lib.common.R;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

/**
 * @author WuPuquan
 * @version 1.0
 * @since 2017/9/19 12:52
 */

public class UiUtil {

    public static final String TRANSACTION_ANIM_LILO = "left_in_left_out";
    public static final String TRANSACTION_ANIM_RIRO = "right_in_right_out";

    /**
     * 切换Fragment
     *
     * @param fragmentManager
     * @param fragment
     * @param containerViewId
     * @param tag
     * @param transactionAnimDirection 转场动画方向 {@link #TRANSACTION_ANIM_LILO} 等
     */
    public static void replaceFragmentWithAnim(@NonNull FragmentManager fragmentManager,
                                               @NonNull Fragment fragment, @IdRes int containerViewId,
                                               String tag, @NonNull String transactionAnimDirection) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (transactionAnimDirection) {
            case TRANSACTION_ANIM_LILO: // 左进左出
                transaction.setCustomAnimations(R.anim.push_left_in, R.anim.push_right_out);
                break;
            case TRANSACTION_ANIM_RIRO: // 右进右出
                transaction.setCustomAnimations(R.anim.push_right_in, R.anim.push_left_out);
                break;
        }
        transaction.replace(containerViewId, fragment, tag);
        transaction.commitAllowingStateLoss();
//        fragmentManager.executePendingTransactions();
    }

    public static void replaceFragment(@NonNull FragmentManager fragmentManager,
                                       @NonNull Fragment fragment, @IdRes int containerViewId, String tag) {
        replaceFragmentWithAnim(fragmentManager, fragment, containerViewId, tag, "");
    }

    public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, @NonNull Fragment fragment, int frameId) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(frameId, fragment);
        transaction.commit();
    }

    public static boolean isActivityFinishingOrDestroyed(@Nullable Activity activity) {
        return activity == null || activity.isFinishing() || activity.isDestroyed();
    }
}
